<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8"/>
  <meta http-equiv="Access-Control-Allow-Origin" content="*" />
  <title>kindle时钟、日历、气温</title>
  <style>
    .page { width: 100%; height: 100%; }
    .time_container, .date_container { width: 100%; margin: auto; text-align: center; }
    .date { font-size: 1.8rem; }
    .time { font-size: 4.8rem; }
    .calendar_{ width: 100%; }
    .root_head { font-size: 2.2rem; margin: 0; padding: 0; height: 30px; border: 2px solid; }
    .root { font-size: 1.2rem; margin: 0; padding: 0; height: 60px; border-width: 0px 2px 2px 2px;border-style:solid; }
    .item {
      list-style: none;
      width: 14.1%;
      height: 60px;
      border-right: 2px solid;
      text-align: center;
      float: left;
    }
    .item.li-head { height: 30px; font-size: 1.2rem; }
    .item:nth-child(7n){ border-right: none; }
    .white_black{color: #000000; background-color: #ffffff;}
    .black_white{color: #ffffff; background-color: #000000;}
    .calendar_data u{
      font-size: 0.8em;
      display: block;
      text-decoration:none;
      position:absolute;
      width:26px;
      height:26px;
      text-align:center;
    }
  </style>
</head>

<body class="white_black">
  <div class="page">
    <div class="date_container">
      <div class="date" id="date">
        <span id="day_y">1989</span>/<span id="day_m">5</span>/<span id="day_d">20
        </span>星期<span id="week_i">六</span>
        <span id="wen_time" style="font-size: 0.4em">052000</span>
        <span id="wen_du">-</span>℃
      </div>
    </div>
    <div class="time_container">
      <div class="time" id="time">
        <span id="time_h">12</span>:<span id="time_m">34</span>.<span id="time_s">**</span>&nbsp;<span id="time_e">秒</span>
      </div>
      <div><span id="nong_li" style="font-size: 1.4em">一九八九(己巳蛇)年四月十六</span></div>
    </div>
    <div class="calendar_">
      <div><ul id="week_header" class="root_head"></ul></div>
      <div id="calendar_data" class="calendar_data"></div>
    </div>
    <div>
      <span id="year_rem_days" style="font-size: 1.2em">今年总天数 x,已度过 x,占比 x,剩余 x</span>
      <a href="javascript:void(0)" onclick="location.reload()" >刷新</a>
    </div>
  </div>
<script src="../lunar/lunar.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript" charset="UTF-8">
(function () {
  var tmp = {minutes:-1,hours:-1,date:-1,month:-1,year:-1,start:-1},
  api = {point:-1,token:'',longitude:'114.53',latitude:'38.03',realtime:''},
  weekList = ['日','一','二','三','四','五','六'];
  function byId(id){ return document.getElementById(id);}
  var id_s = byId("time_s"),li0,li1,time = 1000,
  white = 'white_black',black = 'black_white';
  function now_date(){ return new Date();}

  function updateText(el,num,key){
    if( num === tmp[key] ){ return true; }
    tmp[key] = num; byId(el).innerText = ('0' + num).slice(-2); return false;
  }
  function calendarDataReset(date,startIndex) {
    // 本月天数
    var date_s = new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
    // 日志内容重置
    var items = document.getElementsByClassName('li-data'),max = startIndex + date_s;
    // 获取农历-月
    var month = SolarMonth.fromDate(date),days = month.getDays();
    for (var i = 0,len = items.length; i < len; i++) {
      if(i >= max || i < startIndex){
        items[i].innerHTML = '-'; continue;
      }
      var ind = i - startIndex,dl = days[ind].getLunar();
      var h = HolidayUtil.getHoliday(days[ind].toYmd()),t = '';
      if(h){ t = '<u>' +(h.isWork()?'班':'休')+ '</u>'; }
      t += (ind + 1) + '<br/>';
      t += dl.getDay()===1 ? ('<b>'+ dl.getMonthInChinese() +'月</b>'):('<i>'+ dl.getDayInChinese() +'</i>');
      items[i].innerHTML = t;
    }
  }
  function dateSelect() {
    var b_cla = document.body.className,s_cla = white !== b_cla ? white : black,ss = ' ' + s_cla;
    // 清理高亮元素
    var s_s = document.getElementsByClassName(s_cla);
    for(var i = 0,l = s_s.length,s_,c_; i < l; i++){
      s_ = s_s[0];
      c_ = s_.className;
      s_.className = c_.replace(ss,'');
    }
    // 高亮元素
    li0.className += ss; li1.className += ss;
  }
  function yearRemDays(date){
    //计算年剩余天数,年结束、开始时间、每天秒数
    var end = new Date(date.getFullYear(),11,31,23,59,59),
    start = new Date(date.getFullYear()-1,11,31,23,59,59), dayMs = 24*60*60*1000;
    // 总天数,当前天数
    var tot = Math.round((end.getTime()-start.getTime())/dayMs),
        us = Math.round((date.getTime()-start.getTime())/dayMs);
    byId("year_rem_days").innerText = '年天数 '+tot+',已过 '+us+',占 '+Math.round((us*100)/tot)+'%,余 '+(tot-us);
  }
  function calendarInit(date) {
    // 日历内容 初始化
    var len = weekList.length,htm_s = '';
    var li_1 = '<li class="item',li_2 = '" >',close = "</li>";
    var li_h=' li-head li-h-',li_d=' li-data li-d-';

    // 初始化日历头
    for (var i = 0; i < weekList.length; i++) { htm_s += li_1 + li_h + i + li_2 + weekList[i] + close; }
    byId("week_header").innerHTML = htm_s;
    // 初始化日历内容
    htm_s = '';
    for (var line = 0; line < 6; line++) {
      htm_s += '<div><ul class="root">';
      for (var i = 0; i < len; i++) { htm_s += li_1 + li_d + (line * len + i) + li_2 + '-' + close; }
      htm_s += '</ul></div>';
    }
    byId("calendar_data").innerHTML = htm_s;

    yearRemDays(date);
  }
  function apiInit(date){
    // 天气 获取的特定分钟 初始化
    if( api.point === -1 ){ api.point = date.getMinutes(); }
    // 天气 请求参数 初始化
    if(location.search){
      // 获取 url的参数
      var params = new URLSearchParams(location.search);
      if(params.get('token')){ api['token'] = params.get('token'); }
      if(params.get('longitude')){ api['longitude'] = params.get('longitude'); }
      if(params.get('latitude')){ api['latitude'] = params.get('latitude'); }
    }
    if(api['token']&&api['longitude']&&api['latitude']){
      api['realtime'] = 'https://api.caiyunapp.com/v2.5/'+api['token']+'/'+api['longitude']+','+api['latitude']+'/realtime.jsonp?callback=_ajax_realtime';
    }else{
      api.point = -1;
      byId('wen_du').innerText = '-- --';
      byId('wen_time').innerText = 'INIT ERR';
    }
  }
  function jieJiaRi(fs,f){ if (f) { for (var i=0,j=f.length;i<j;i++){ fs.push(f[i]); } } }
  function nongLi(date){
    // 农历-当天
    var nl = Solar.fromDate(date),d = nl.getLunar(),fs = [];
    jieJiaRi(fs,d.getFestivals());
    jieJiaRi(fs,d.getOtherFestivals());
    jieJiaRi(fs,nl.getFestivals());
    jieJiaRi(fs,nl.getOtherFestivals());
    var h = HolidayUtil.getHoliday(nl.getYear(), nl.getMonth(), nl.getDay());
    if (h) {fs.push(h.getName()+(h.isWork()?'调休':'放假'));}
    // console.log('节日/纪念日',fs.join(' '));
    byId('nong_li').innerText = d.getYearInGanZhi()+' '+d.getYearShengXiao()+'年 '+d.getMonthInChinese()+'月 '+d.getDayInChinese() + " " + fs.join('、');
  }
  //跨域请求
function request_get_p() {
  // 删除上次的请求痕迹
  var scripts = document.getElementsByTagName('script');
  if(scripts['jsonp_id']){ scripts['jsonp_id'].parentNode.removeChild(scripts['jsonp_id']);}
  // 创建一个script元素
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = api['realtime'];
  script.id = 'jsonp_id';
  document.head.appendChild(script);
}
var skycon = {'CLEAR_DAY':'晴天','CLEAR_NIGHT':'晴夜','PARTLY_CLOUDY_DAY':'云天','PARTLY_CLOUDY_NIGHT':'云夜','CLOUDY':'阴天','LIGHT_HAZE':'轻霾','MODERATE_HAZE':'中霾','HEAVY_HAZE':'重霾','LIGHT_RAIN':'小雨','MODERATE_RAIN':'中雨','HEAVY_RAIN':'大雨','STORM_RAIN':'暴雨','FOG':'雾天','LIGHT_SNOW':'小雪','MODERATE_SNOW':'中雪','HEAVY_SNOW':'大雪','STORM_SNOW':'暴雪','DUST':'浮尘','SAND':'沙尘','WIND':'大风'};
// 接口回调
window._ajax_realtime = function(res) {
  if(res.result && res.result.realtime&& res.result.realtime.status === 'ok'){
    var realtime = res.result.realtime;
    byId('wen_du').innerText = skycon[realtime.skycon]+' '+realtime.temperature;
    var d = new Date();
    byId('wen_time').innerText=d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();
  }
}
  function updateDate() {
    var date = now_date();
    // 秒
    id_s.innerText = ('0' + date.getSeconds()).slice(-2);
    // 分钟
    if( updateText("time_m",date.getMinutes(),'minutes') ){ return; }
    // 获取 天气信息 每小时特定分钟触发
    if( api.point === tmp.minutes ){ request_get_p(); }
    // 反显 分钟数是10的倍数，0也算
    if( tmp.start !== -1 && tmp.minutes % 20 === 0){
      var b1 = document.body.className , d1 = b1 === white ? black : white;
      document.body.className = d1;
      li0.className = li0.className.replace(d1,b1);
      li1.className = li1.className.replace(d1,b1);
    }
    // 小时
    if( updateText("time_h",date.getHours(),'hours') ){ return; }
    // 日
    if( updateText("day_d",date.getDate(),'date') ){ return; }
    nongLi(date);
    // 星期
    byId("week_i").innerText = weekList[date.getDay()];
    // 计算年剩余天数
    yearRemDays(date);
    // 本月第一天星期几
    tmp.start = new Date(date.getFullYear(), date.getMonth(), 1).getDay();
    li0 = document.getElementsByClassName('li-h-'+date.getDay())[0];
    li1 = document.getElementsByClassName('li-d-'+(tmp.start + date.getDate() - 1))[0];
    // 日选择
    dateSelect();
    // 月
    if( updateText("day_m",date.getMonth() + 1,'month') ){ return; }
    // 日历更新
    calendarDataReset(date,tmp.start);
    // 年
    updateText("day_y",date.getFullYear(),'year');
  }
  // 动态定时器
  window.update_date = function() {
    updateDate();
    if( tmp.hours === -1 ){
      time = 1000;
    }else if( (tmp.hours >= 7 && tmp.hours <= 9) ||
      (tmp.hours >= 13 && tmp.hours <= 15) ){
      // 每秒 更新
      if(time !== 1000){ time=1000; byId("time_e").innerText='秒'; }
    }else if (tmp.hours >= 6 && tmp.hours <= 20) {
      // 每分 更新
      if(time !== 60000){ time=60*1000; byId("time_e").innerText='分'; }
    }else{
      // 每60分 更新
      if(time !== 3600000){ time=60*60*1000; byId("time_e").innerText='时'; }
    }
    setTimeout("update_date()", time);
  }
  var date_now = now_date();
  calendarInit(date_now);
  apiInit(date_now);
  update_date();
})();
</script>
</body>
</html>
